package org.example.Thread.B_Thread;

/**
 * @className: Race
 * @author: 芃
 * @description: 模拟龟兔赛跑（兔子睡觉版）
 * @date: 2024/5/13 11:07
 */
public class Race implements Runnable {
    //胜利者
    private static String winner;
    @Override
    public void run() {
        for (int i = 0; i <= 1000; i++) {
            //模拟兔子休息
            if(Thread.currentThread().getName().equals("兔子")){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            //判断是否比赛是否结束
            boolean flag = gameOver(i);
            if (flag){
                break;
            }
            System.out.println(Thread.currentThread().getName() + "---》跑了" + i+ "步");
        }
    }
    //判断是否完成比赛
    private boolean gameOver(int step){
        //判断是否有胜利者
        if (winner != null){//已经存在胜利者了
            return true;
        }else{//没有胜利者
            if (step == 1000){
                winner = Thread.currentThread().getName();
                System.out.println(winner + "---》胜利了！");
                return true;
            }else{
                return false;
            }
        }
    }

    public static void main(String[] args) {
        Race race = new Race();
        Thread t1 = new Thread(race,"兔子");
        Thread t2 = new Thread(race,"龟子");
        t1.start();
        t2.start();
    }
}
